package GoodsActivityService

import (
	"context"
	"fmt"
	"gdshop-back-end-go/common/entity"
	"github.com/gogf/gf/encoding/gjson"
)

func GetMaxDiscountActivityByGoodsId(ctx context.Context, goodsId int, totalPrice int64) (*entity.GoodsActivity,
	int64, error) {

	activitys, err := GetGoodsActivityByGoodsId(ctx, goodsId)
	if err != nil {
		return nil, 0, err
	}

	var discountMoney int64 = 0
	nowActivity := (*entity.GoodsActivity)(nil)

	for _, item := range activitys {
		// 暂时先处理 activity_type == 1 == 2 的情况
		if item.ActivityType != 1 && item.ActivityType != 2 {
			continue
		}

		// 解析规则
		json, err := gjson.LoadContent(item.Rules)
		if err != nil {
			return nil, 0, err
		}
		var tmps []*entity.RulesItem
		err = json.Structs(&tmps)
		if err != nil {
			return nil, 0, err
		}
		if len(tmps) < 1 {
			// 防止出错
			continue
		}

		// 处理 loop == 1 的
		if item.Loop == 1 {
			// 每满 减(折)
			if tmps[0].ThresholdNum > totalPrice {
				// 总支付金额 不超过 门槛
				continue
			}
			var tmpDiscountMoney float64 = 0
			// 减
			if item.ActivityType == 2 {
				// 每满减实际就是折扣
				tmpDiscountMoney = float64(totalPrice) *
					float64(tmps[0].DiscountNum) / float64(tmps[0].ThresholdNum)
			}
			// 折
			if item.ActivityType == 1 {
				tmpDiscountMoney = float64(totalPrice) - float64(totalPrice)*
					float64(tmps[0].DiscountNum)/1000.00
			}
			if discountMoney > int64(tmpDiscountMoney) {
				continue
			}
			discountMoney = int64(tmpDiscountMoney)
			nowActivity = item
		} else {
			for _, r := range tmps {
				if r.ThresholdNum > totalPrice {
					continue
				}

				var tmpDiscountMoney float64 = 0
				// 减
				if item.ActivityType == 2 {
					// 每满减实际就是折扣
					tmpDiscountMoney = float64(r.DiscountNum)
				}
				// 折
				if item.ActivityType == 1 {
					tmpDiscountMoney = float64(totalPrice) - float64(totalPrice)*
						float64(tmps[0].DiscountNum)/1000.00
				}

				if discountMoney > int64(tmpDiscountMoney) {
					// 上一个优惠金额，大于当前，则循环下一个活动
					continue
				}

				discountMoney = int64(tmpDiscountMoney)
				nowActivity = item
			}
		}

		fmt.Println("----------------选中 ", nowActivity, " 优惠 ", discountMoney)
	}

	return nowActivity, discountMoney, nil
}
